<template>
  <div class="form-container">
    <el-row type="flex" justify="center">
      <el-form style="width:100%;" ref="form" :model="form" :rules="formRules" label-position="left" label-width="135px">
        <!-- 贷款类型 -->
        <el-row type="flex" justify="center" v-if="isDisplay('type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.loanType')" prop="type">
              <el-radio-group v-model="form.type" @change="loanTypeChangeHandler">
                <el-radio v-for="loanType in loanTypes" :disabled="isUpdateProduct()" :label="loanType.value" :key="'loanType'+loanType.value">{{loanType.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 基本信息 -->
        <el-row type="flex" justify="center" style="margin-top: 10px">
          <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
            <form-divider :text="$t('production.basicInfo')"></form-divider>
          </el-col>
        </el-row>
        <!-- 产品名称 -->
        <el-row type="flex" justify="center" v-if="isDisplay('title')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.productionName')" prop="title">
              <el-input v-model="form.title" :placeholder="$t('production.productionNameInput')"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 产品类型 -->
        <el-row type="flex" justify="center" v-if="isDisplay('product_type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.productType')" prop="product_type">
              <el-select
                v-model="form.product_type" 
                name="product_type" 
                :placeholder="$t('select')"
                style="width:100%;">
                <el-option v-for="productType in productTypes" :label="productType.name" :value="productType.value" :key="'productType' + productType.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 服务种类 -->
        <el-row type="flex" justify="center" v-if="isDisplay('service_type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.serviceType')" prop="service_type">
              <el-select
                v-model="form.service_type" 
                name="service_type" 
                :placeholder="$t('select')"
                style="width:100%;">
                <el-option v-for="serviceType in serviceTypes" :label="serviceType.name" :value="serviceType.value" :key="'serviceType' + serviceType.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 额度范围 -->
        <el-row type="flex" justify="center" v-if="isDisplay('min_deposit')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-row>
              <el-col style="max-width: 135px;">
                <el-form-item :label="$t('production.limitRange')" required>
                </el-form-item>
              </el-col>
              <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
                <el-form-item prop="min_deposit" class="inner-form-item">
                  <el-input v-model.number="form.min_deposit" :placeholder="''">
                    <i v-if="form.type === '2'"
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      万
                    </i>
                    <i v-if="form.type === '1'"
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      元
                    </i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col style="text-align: center;" :xs="1" :sm="1" :md="1" :lg="1" :xl="1">
                <span style="line-height: 40px;">-</span>
              </el-col>
              <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
                <el-form-item prop="max_deposit" class="inner-form-item">
                  <el-input v-model.number="form.max_deposit" :placeholder="''" @change="validateOtherField('min_deposit')">
                    <i v-if="form.type === '2'"
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      万
                    </i>
                    <i v-if="form.type === '1'"
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      元
                    </i>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 贷款期限 -->
        <el-row type="flex" justify="center" v-if="isDisplay('min_time_limit')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-row>
              <el-col style="max-width: 135px;">
                <el-form-item :label="$t('production.loanTimeRange')" required>
                </el-form-item>
              </el-col>
              <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
                <el-form-item prop="min_time_limit" class="inner-form-item">
                  <el-input v-model.number="form.min_time_limit" :placeholder="''">
                    <!-- <i class="iconfont el-input__icon suffix-icon-day" slot="suffix">
                      天
                    </i> -->
                    <i class="iconfont el-input__icon suffix-icon-day" slot="suffix">
                      月
                    </i>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col style="text-align: center;" :xs="1" :sm="1" :md="1" :lg="1" :xl="1">
                <span style="line-height: 40px;">-</span>
              </el-col>
              <el-col :xs="7" :sm="7" :md="7" :lg="7" :xl="7">
                <el-form-item prop="max_time_limit" class="inner-form-item">
                  <el-input v-model.number="form.max_time_limit" :placeholder="''" @change="validateOtherField('min_time_limit')">
                    <!-- <i
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      天
                    </i> -->
                    <i
                      class="iconfont el-input__icon suffix-icon-day"
                      slot="suffix">
                      月
                    </i>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 抵押类型 -->
        <el-row type="flex" justify="center" v-if="isDisplay('mortgage_type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.pledgeType')" prop="mortgage_type">
              <el-select
                v-model="form.mortgage_type" 
                name="mortgage_type" 
                :placeholder="$t('select')"
                style="width:100%;">
                <el-option v-for="pledgeType in pledgeTypes" :label="pledgeType.name" :value="pledgeType.value" :key="'pledgeType' + pledgeType.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 放款时间 -->
        <el-row type="flex" justify="center" v-if="isDisplay('loan_time')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.lendingTime')" prop="loan_time">
              <el-radio-group v-model="form.loan_time" @change="loanTimeTypeChangeHandler">
                <el-radio :label="'1'">
                  <el-form-item prop="lendingTimeFrom" class="check-box-form-item">
                    <el-input :disabled="form.loan_time !== '1'" v-model.number="form.lendingTimeFrom" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        天
                      </i>
                    </el-input>
                  </el-form-item>
                  <span>-</span>
                    <el-form-item prop="lendingTimeTo" class="check-box-form-item">
                      <el-input :disabled="form.loan_time !== '1'" v-model.number="form.lendingTimeTo" :placeholder="''" class="rate-input" @change="validateOtherField('lendingTimeFrom')">
                        <i
                          class="iconfont el-input__icon suffix-icon-day"
                          slot="suffix">
                          天
                        </i>
                      </el-input>
                    </el-form-item>
                </el-radio>
                <el-radio :label="'2'">
                  <el-form-item prop="lendingTimeMin" class="check-box-form-item">
                    <el-input :disabled="form.loan_time !== '2'" v-model.number="form.lendingTimeMin" :placeholder="''" class="rate-input" style="width: 100px;">
                      <i
                        class="iconfont el-input__icon suffix-icon-day-min"
                        slot="suffix">
                        天以上
                      </i>
                    </el-input>
                  </el-form-item>
                </el-radio>
                <el-radio :label="'3'">
                  <span>当日放款</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 城市 -->
        <el-row type="flex" justify="center" v-if="isDisplay('city_code')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.city')" prop="city_code">
              <!-- <area-cascader v-model="form.city" :data="pca" size="large"></area-cascader> -->
              <!-- <el-cascader
                size="large"
                :options="options"
                v-model="form.city">
              </el-cascader> -->
              <provice-city-cascade :city-multiple="isCityMultiple" v-on:city:change="cityChangeHandler"></provice-city-cascade>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 公司logo -->
        <el-row type="flex" justify="center" v-if="isDisplay('logo')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.companyLogo')" prop="logo">
              <el-upload
                class="logo-uploader"
                action=""
                :http-request="uploadLogo"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload">
                <img v-if="form.logo" :src="form.logo" class="logo">
                <i v-else class="el-icon-plus logo-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 收费方式 -->
        <el-row type="flex" justify="center">
          <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
            <form-divider :text="$t('production.chargeWay')"></form-divider>
          </el-col>
        </el-row>
        <!-- 平均每月综合费率 -->
        <el-row type="flex" justify="center" v-if="isDisplay('combination_rate_type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.averageMonthlyCompositeRate')" prop="combination_rate_type">
              <el-radio-group v-model="form.combination_rate_type" @change="combinationRateTypeChangeHandler">
                <el-radio v-for="(feeRateType, index) in feeRateTypes" :label="feeRateType.value" :key="'average' + feeRateType.value">
                  <el-form-item v-if="index === 0" prop="averageMonthlyFeeRate" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.combination_rate_type !== 1" v-model.number="form.averageMonthlyFeeRate" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <!-- <el-form-item v-if="index === 0" prop="averageMonthlyFeeRateMin" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.combination_rate_type !== 1" v-model.number="form.averageMonthlyFeeRateMin" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <span v-if="index === 0">-</span>
                  <el-form-item v-if="index === 0" prop="averageMonthlyFeeRateMax" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.combination_rate_type !== 1" v-model.number="form.averageMonthlyFeeRateMax" :placeholder="''" class="rate-input" @change="validateOtherField('averageMonthlyFeeRateMin')">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item> -->
                  <span v-if="index !== 0">{{feeRateType.name}}</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 一次性费用 -->
        <el-row type="flex" justify="center" v-if="isDisplay('disposable_cost_type')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.oneTimeCharge')" prop="disposable_cost_type">
              <el-radio-group v-model="form.disposable_cost_type" @change="disposableCostTypeChangeHandler">
                <el-radio v-for="(feeRateType, index) in feeRateTypes" :label="feeRateType.value" :key="'oneTimeFee' + feeRateType.value">
                  <el-form-item v-if="index === 0" prop="oneTimeFeeRate" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.disposable_cost_type !== 1" v-model.number="form.oneTimeFeeRate" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <!-- <el-form-item v-if="index === 0" prop="oneTimeFeeRateMin" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.disposable_cost_type !== 1" v-model.number="form.oneTimeFeeRateMin" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <span v-if="index === 0">-</span>
                  <el-form-item v-if="index === 0" prop="oneTimeFeeRateMax" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.disposable_cost_type !== 1" v-model.number="form.oneTimeFeeRateMax" :placeholder="''" class="rate-input" @change="validateOtherField('oneTimeFeeRateMin')">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item> -->
                  <span v-if="index !== 0">{{feeRateType.name}}</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 担保金比率 -->
        <el-row type="flex" justify="center" v-if="isDisplay('collateralRatioType')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.collateralRatio')" prop="collateralRatioType">
              <el-radio-group v-model="form.collateralRatioType" @change="collateralRatioTypeChangeHandler">
                <el-radio v-for="(feeRateType, index) in feeRateTypes" :label="feeRateType.value" :key="'collateralRatio' +  feeRateType.value">
                  <el-form-item v-if="index === 0" prop="collateralRatioMin" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.collateralRatioType !== 1" v-model.number="form.collateralRatioMin" :placeholder="''" class="rate-input">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <span v-if="index === 0">-</span>
                  <el-form-item v-if="index === 0" prop="collateralRatioMax" class="check-box-form-item">
                    <el-input v-if="index === 0" :disabled="form.collateralRatioType !== 1" v-model.number="form.collateralRatioMax" :placeholder="''" class="rate-input" @change="validateOtherField('collateralRatioMin')">
                      <i
                        class="iconfont el-input__icon suffix-icon-day"
                        slot="suffix">
                        %
                      </i>
                    </el-input>
                  </el-form-item>
                  <span v-if="index !== 0">{{feeRateType.name}}</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 放款后收费 -->
        <el-row type="flex" justify="center" v-if="isDisplay('charge_money')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.chargeAfterLoan')" prop="charge_money">
              <el-radio-group v-model="form.charge_money">
                <el-radio v-for="(type) in chargeAfterLoanTypes" :label="type.value" :key="'chargeAfterLoanType'+type.value">
                  <span>{{type.name}}</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 产品详细描述（请根据产品特点选择性填写） -->
        <el-row type="flex" justify="center" style="margin-top: 10px">
          <el-col :xs="24" :sm="16" :md="16" :lg="16" :xl="16">
            <form-divider :text="$t('production.productFeatures')"></form-divider>
          </el-col>
        </el-row>
        <!-- 产品特点 -->
        <el-row type="flex" justify="center" v-if="isDisplay('product_feature')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.productFeature')">
              <el-input
                type="textarea"
                :rows="3"
                :placeholder="$t('production.productFeatureInput')"
                v-model="form.product_feature">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 申请条件 -->
        <el-row type="flex" justify="center" v-if="isDisplay('apply_for_position')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.applicationRequirements')">
              <el-input
                type="textarea"
                :rows="4"
                :placeholder="$t('production.applicationRequirementsInputTips')"
                v-model="form.apply_for_position">
              </el-input>
              <!-- <el-input v-model="form.apply_for_position" :placeholder="''" class="application-input">
                <i
                  class="iconfont el-input__icon"
                  slot="prefix">
                  {{$t('production.applicationDemands')}}:
                </i>
              </el-input>
              <el-input v-model="form.creditDemands" :placeholder="''" class="application-input">
                <i
                  class="iconfont el-input__icon"
                  slot="prefix">
                  {{$t('production.creditDemands')}}:
                </i>
              </el-input>
              <el-input v-model="form.debtDemands" :placeholder="''" class="application-input">
                <i
                  class="iconfont el-input__icon"
                  slot="prefix">
                  {{$t('production.debtDemands')}}:
                </i>
              </el-input>
              <el-input v-model="form.otherDemands" :placeholder="''" class="application-input">
                <i
                  class="iconfont el-input__icon"
                  slot="prefix">
                  {{$t('production.otherDemands')}}:
                </i>
              </el-input> -->
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 所需材料特点 -->
        <el-row type="flex" justify="center" v-if="isDisplay('material_requested')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.requiredMaterial')">
              <el-input
                type="textarea"
                :rows="3"
                :placeholder="$t('')"
                v-model="form.material_requested">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 利率说明 -->
        <el-row type="flex" justify="center" v-if="isDisplay('rate_description')">
          <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
            <el-form-item :label="$t('production.interestRateInstructions')">
              <el-input
                type="textarea"
                :rows="3"
                :placeholder="$t('')"
                v-model="form.rate_description">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 提交 -->
        <el-row type="flex" justify="center">
          <el-button type="primary" @click.native.prevent="onSubmit">{{$t('submit')}}</el-button>
        </el-row>
      </el-form>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { provinceAndCityData } from 'element-china-area-data'
import { default as FormDivider } from '../formDivider/index'
import { default as ProviceCityCascade } from '@/components/ProviceCityCascade/index'
import { 
  isValidateProductName, 
  rangeValidate, 
  validateMinAndMax,
  validateNumberRange
} from '../../../utils/validate'
import { getCityNameByCode } from '@/utils/chinaArea'

import _ from 'lodash'

export default {
  name: "ProductionEdit",
  components: {
    FormDivider,
    ProviceCityCascade
  },
  computed: {
    ...mapGetters([
      'token',
    ]),
  },
  data() {
    const that = this
    const validateProductName = (rule, value, callback) => {
      if (!isValidateProductName(value)) {
        callback(new Error(this.$t("production.productNameValidateTips")))
      } else {
        callback()
      }
    }
    // 额度范围最小最大值校验
    const depositValidateRange = (rule, value, callback) => {
      if (this.form.min_deposit > 0 && this.form.max_deposit 
        && this.form.min_deposit > this.form.max_deposit) {
        callback(new Error(this.$t('production.depositRangeCompareTips')))
      } else {
        callback()
      }
    }
    // 贷款期限最小最大值校验
    const loanTimeValidateRange = (rule, value, callback) => {
      if (this.form.min_time_limit > 0 && this.form.max_time_limit > 0 
        && this.form.min_time_limit > this.form.max_time_limit) {
        callback(new Error(this.$t('production.loanTimeRangeCompareTips')))
      } else {
        callback()
      }
    }
    // 放款时间最小最大值校验
    const lendingTimeValidateRange = (rule, value, callback) => {
      if (this.form.lendingTimeFrom > 0 && this.form.lendingTimeTo > 0 
        && this.form.lendingTimeFrom >= this.form.lendingTimeTo) {
        callback(new Error(this.$t('production.lendingTimeRangeCompareTips')))
      } else {
        callback()
      }
    }
    // 平均每月综合费率最小最大值校验
    const averageMonthlyRateValidateRange = (rule, value, callback) => {
      if (this.averageMonthlyFeeRateMin > 0 && this.averageMonthlyFeeRateMax > 0 
        && this.form.averageMonthlyFeeRateMin >= this.form.averageMonthlyFeeRateMax) {
        callback(new Error(this.$t('production.averageMonthlyCompositeRateCompareTips')))
      } else {
        callback()
      }
    }
    // 一次性费用最小最大值校验
    const disposableCostValidateRange = (rule, value, callback) => {
      if (this.form.oneTimeFeeRateMin > 0 && this.form.oneTimeFeeRateMax > 0 
        && this.form.oneTimeFeeRateMin >= this.form.oneTimeFeeRateMax) {
        callback(new Error(this.$t('production.oneTimeCostCompareTips')))
      } else {
        callback()
      }
    }
    // 担保金比率最小最大值校验
    const collateralRatioRange = (rule, value, callback) => {
      if (this.form.collateralRatioMin > 0 && this.form.collateralRatioMax > 0 
        && this.form.collateralRatioMin >= this.form.collateralRatioMax) {
        callback(new Error(this.$t('production.collateralRatioCompareTips')))
      } else {
        callback()
      }
    }

    return {
      loanTypes: [
        {
          name: "极速贷",
          value: "1"
        },
        {
          name: "银行贷",
          value: "2"
        },
      ],
      // 产品类型
      productTypes: [
        {
          name: "工薪贷",
          value: 1
        }, {
          name: "生意贷",
          value: 2
        }, {
          name: "车抵贷",
          value: 3
        }, {
          name: "房抵贷",
          value: 4
        }
      ],
      // 服务种类
      serviceTypes: [{
          name: "出借服务",
          value: 1
        }, {
          name: "中介服务",
          value: 2
        }, {
          name: "担保服务",
          value: 3
        }
      ],
      // 抵押类型
      pledgeTypes: [
        {
          name: "无需抵押",
          value: 1
        }, {
          name: "房产抵押",
          value: 2
        }, {
          name: "车辆抵押",
          value: 3
        }
      ],
      lendingTimeTypes: [
        {
          name: "n日内",
          value: 1
        },
        {
          name: "n日以上",
          value: 2
        },
        {
          name: "当天放款",
          value: 3
        }
      ],
      feeRateTypes: [{
        name: 'range',
        value: 1
      }, {
        name: '面议',
        value: 2,
      }, {
        name: '无此费用',
        value: 3,
      }],
      chargeAfterLoanTypes: [{
        name: '可以承诺',
        value: 1
      }, {
        name: '无法承诺',
        value: 2
      }],
      // 表单对象
      form: {
        
      },
      // form 校验规则
      formRules: {
        
      },
      // 公共的字段名
      publicFields: ['type', 'title', 'min_deposit', 'max_deposit', 'min_time_limit', 'max_time_limit',
       'loan_time', 'lendingTimeFrom', 'lendingTimeMin', 'city_code', 'logo', 'disposable_cost_type', 'oneTimeFeeRate', 'oneTimeFeeRateMin', 'oneTimeFeeRateMax',
       'combination_rate_type', 'averageMonthlyFeeRate', 'averageMonthlyFeeRateMin', 'averageMonthlyFeeRateMax', 
       'product_feature', 'apply_for_position', 'creditDemands', 'debtDemands', 'otherDemands',
       'material_requested', 'rate_description'], 
      // 银行贷和极速贷都有的字段
      publicForm: {
        // 贷款类型 '1':极速贷， '2':银行贷
        type: "1",
        // 产品名称
        title: "",
        // 额度范围 开始
        min_deposit: '',
        // 额度范围 结束
        max_deposit: '',
        // 贷款期限 开始
        min_time_limit: "",
        // 贷款期限 结束
        max_time_limit: "",
        // 放款时间类型
        loan_time: '1',
        // 放款时间 最小天数
        lendingTimeFrom: 1,
        // 放款时间 最大天数
        lendingTimeTo: "",
        // 放款时间 n天以上
        lendingTimeMin: 1,
        // 服务城市
        city_code: [],
        // 公司logo的url
        logo: 'https://avatars1.githubusercontent.com/u/28702748?s=40&v=4',
        // 平均每月综合费率类型
        combination_rate_type: 1,
        // 平均每月综合费率范围最小值
        averageMonthlyFeeRateMin: '',
        // 平均每月综合费率范围最大值
        averageMonthlyFeeRateMax: '',
        // 一次性费用类型
        disposable_cost_type: 1,
        // 一次性费用范围最小值
        oneTimeFeeRateMin: '',
        // 一次性费用范围最大值
        oneTimeFeeRateMax: '',
        // 产品特性
        product_feature: '',
        // 申请要求
        apply_for_position: '',
        // // 信用要求
        // creditDemands: '',
        // // 负债要求
        // debtDemands: '',
        // // 其他要求
        // otherDemands: '',
        // 所需材料
        material_requested: '',
        // 利率说明
        rate_description: ''
      },
      // 银行贷字段名
      bankLoanFields: ['product_type', 'service_type', 'mortgage_type', 'collateralRatioType', 'collateralRatioMin', 'collateralRatioMax', 'charge_money'],
      // 银行贷有的字段 缓存
      bankLoanForm: {
        // 产品类型
        product_type: '',
        // 服务种类
        service_type: '',
        // 抵押类型
        mortgage_type: '',
        // 担保金比率类型
        collateralRatioType: 1,
        // 担保金比率最小值
        collateralRatioMin: '',
        // 担保金比率最大值
        collateralRatioMax: '',
         // 放款后收费类型
        charge_money: '',
      },
      // 极速贷的字段 用作缓存
      fastLoanForm: {

      },
      // publicForm 校验规则
      publicFormRules: {
        type: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.typeRequired")
        }],
        title: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.productNameRequired")
        }, {
            validator: validateProductName,
            message: this.$t("production.productNameValidateTips")
        }],
        min_deposit: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.limitRequired")
        }, { 
          validator: depositValidateRange,
          trigger: 'blur',
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        max_deposit: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.limitRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        min_time_limit: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.loanDueTimeRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }, {
          validator: loanTimeValidateRange,
          message: this.$t('production.loanTimeRangeCompareTips')
        }],
        max_time_limit: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.loanDueTimeRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        lendingTimeMin: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.loanDueTimeRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        loan_time: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.lendingTimeTypeRequired")
        }],
        lendingTimeFrom: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.lendingTimeTypeRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }, {
          validator: lendingTimeValidateRange,
          message: this.$t('production.lendingTimeRangeCompareTips')
        }],
        lendingTimeTo: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.lendingTimeTypeRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        city_code: [{
            required: true,
            trigger: "blur",
            message: this.$t("production.cityRequired")
        }],
        logo: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        combination_rate_type: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        // averageMonthlyFeeRateMin: [{
        //     required: true,
        //     trigger: "blur",
        //     message: this.$t("fieldRequired")
        // }, {
        //   type: 'number', 
        //   message: this.$t("production.numberRequired")
        // }, {
        //   validator: averageMonthlyRateValidateRange,
        //   message: this.$t('production.averageMonthlyCompositeRateCompareTips')
        // }],
        // averageMonthlyFeeRateMax: [{
        //     required: true,
        //     trigger: "blur",
        //     message: this.$t("fieldRequired")
        // }, {
        //   type: 'number', 
        //   message: this.$t("production.numberRequired")
        // }],
        // 月综合费率
        averageMonthlyFeeRate: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        disposable_cost_type: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        // oneTimeFeeRateMin: [{
        //     required: true,
        //     trigger: "blur",
        //     message: this.$t("fieldRequired")
        // }, {
        //   type: 'number', 
        //   message: this.$t("production.numberRequired")
        // }, {
        //   validator: disposableCostValidateRange,
        //   message: this.$t('production.oneTimeCostCompareTips')
        // }],
        // oneTimeFeeRateMax: [{
        //     required: true,
        //     trigger: "blur",
        //     message: this.$t("fieldRequired")
        // }, {
        //   type: 'number', 
        //   message: this.$t("production.numberRequired")
        // }],
        // 一次性费用
        oneTimeFeeRate: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
      },
      
      bankFormRules: {
        product_type: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        service_type: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        mortgage_type: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        collateralRatioType: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }],
        collateralRatioMin: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }, {
          validator: collateralRatioRange,
          message: this.$t('production.loanTimeRangeCompareTips')
        }],
        collateralRatioMax: [{
            required: true,
            trigger: "blur",
            message: this.$t("fieldRequired")
        }, {
          type: 'number', 
          message: this.$t("production.numberRequired")
        }],
        charge_money: [{
          required: true,
          trigger: "blur",
          message: this.$t("fieldRequired")
        }]
      },
      options: provinceAndCityData,
      // 最小额度的最小值
      minDepositFrom: 1,
      // 最小额度的最大值
      minDepositTo: 3,
      // 最大额度的最小值
      maxDepositFrom: 1,
      // 最大额度的最大值
      maxDepositTo: 999,
      // logo 上传url地址
      imgUploadUrl: 'http://api.erongbank.com/api/upload',
      // 上传时需要带的header参数
      uploadHeader: {
        Authorization: this.token
      },
      // 城市是否多选的设置
      isCityMultiple: true,
      // 快速贷的提交字段名
      fastProductFields: ['product_id', 'title', 'min_deposit', 'max_deposit',
       'loan_time', 'min_time_limit', 'max_time_limit', 'logo',
       'product_feature', 'apply_for_position',
       'material_requested', 'rate_description', 'disposable_cost_type', 'disposable_cost', 'city_code'], 
      // 银行贷提交字段名
      bankProductFields: ['product_id', 'title', 'product_type', 'service_type', 'min_deposit', 'max_deposit', 
       'loan_time', 'min_time_limit', 'max_time_limit', 'logo', 'mortgage_type', 'charge_money', 
       'combination_rate_type', 'combination_rate', 'disposable_cost_type', 'disposable_cost', 
       'product_feature', 'apply_for_position', 'material_requested', 'rate_description', 'city_code'], 
      // 快速产品id
      fastProductId: this.$route.query.fastProductId,
      // 银行产品id
      bankProductId: this.$route.query.bankProductId,
      // 组件中的loading遮罩层对象，调用openFullScreenLoading方法时赋值
      loading: null,
      // 从服务器获取的产品对象
      product: {}
    }
  },
  created() {
    this.initForm()
    this.initEditProduct()
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.type === '1') {
            const fastProductObj = this.fastProductProcess(this.form)
            this.addOrUpdataFastProduct(fastProductObj)
            // console.log('要提交的极速贷数据：', fastProductObj)
          } else if (this.form.type === '2') {
            const bankProductObj = this.bankProductProcess(this.form)
            this.addOrUpdataBankProduct(bankProductObj)
            // console.log('要提交的银行贷数据：', bankProductObj)
          }
        } else {
          console.log("error submit!!")
          return false;
        }
        // 测试，跳转到结果组件
        // this.goToEditProductResult(0)
      });
      console.log('submit form')
    },
    /**
     * 编辑产品初始化方法
     */
    initEditProduct() {
      if (this.bankProductId) {
        this.openFullScreenLoading()
        this.$store.dispatch('getBankProductByID', { id: this.bankProductId })
          .then(data => {
            this.bankProductFormProcess(data)
            this.closeFullScreenLoading()
          }).catch(error => {
            this.fastProductFormProcess(data)
            this.closeFullScreenLoading()

            console.error('init edit bank product has error:', error)
            this.$notify.error({
              title: this.$t('operationFailed'),
              message: this.$t('errorTips'),
            })
          }) 
      } else if (this.fastProductId) {
        this.openFullScreenLoading()
        this.$store.dispatch('getFastProductByID', { id: this.fastProductId })
          .then(data => {
            this.fastProductFormProcess(data)
            this.closeFullScreenLoading()
          }).catch(error => {
            this.closeFullScreenLoading()

            console.error('init edit fast product has error:', error)
            this.$notify.error({
              title: this.$t('operationFailed'),
              message: this.$t('errorTips'),
            })
          }) 
      }
    },
    initForm() {
      // 默认是极速贷form
      this.form = {
        ...this.publicForm
      }
      this.formRules = {
        ...this.publicFormRules
      }

      if (this.bankProductId) {
        this.form.type = '2'

        this.form = {
          ...this.publicForm,
          ...this.bankLoanForm
        }
        this.formRules = {
          ...this.bankFormRules,
          ...this.publicFormRules
        }
      } else {
        this.form.type = '1'
      }
    },
    // 贷款类型改变的处理方法 
    loanTypeChangeHandler() {
      if (this.form.type === '1') {
        // 备份公共字段的数据
        this.publicForm = _.pick(this.form, this.publicFields)
        // 备份银行贷字段的数据
        this.bankLoanForm = _.pick(this.form, this.bankLoanFields)
        // 更新form
        this.form = {
          ...this.publicForm,
          ...this.fastLoanForm
        }
        // 更新rule
        this.formRules = {
          ...this.publicFormRules,
        }
      } else if (this.form.type === '2') {
        // 备份公共字段的数据
        this.publicForm = _.pick(this.form, this.publicFields);
        // 备份极速贷字段的数据(极速贷没有特殊字段，不需备份)
        // 更新form，从backLoanForm中获取缓存数据
        this.form = {
            ...this.publicForm,
            ...this.bankLoanForm
        }
        // 更新rule
        this.formRules = {
          ...this.publicFormRules,
          ...this.bankFormRules
        }
      }

      // 清除表单的校验
      // this.$refs.form.clearValidate()
    },
    /**
     * 获取服务器的银行产品数据后，初始化form的方法
     */
    bankProductFormProcess(data) {
      if (data && data['code'] === 0) {
        this.product = data['data']

        // 初始化form的值
        this.form = Object.assign(this.form, this.product)
        this.form.type = '2'

        // 处理放款时间
        const loanTimeFormObj = this.convertLoanTimeToFormData(this.form.loan_time)
        this.form = Object.assign(this.form, loanTimeFormObj)

        // 转换城市code为城市名  测试用
        this.product.cityNames = this.convertCityOrProvinceCodeToName(['130100', '130200'])
        console.log('cityNames = ', this.product.cityNames)

        // 初始化formRules
        this.loanTimeTypeChangeHandler(this.form.loan_time)
        this.combinationRateTypeChangeHandler(this.form.combination_rate_type)
        this.disposableCostTypeChangeHandler(this.form.disposable_cost_type)
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**
     * 获取服务器的快速产品数据后，初始化form的方法
     */
    fastProductFormProcess(data) {
      if (data && data['code'] === 0) {
        this.product = data['data']

        // 初始化form的值
        this.form = Object.assign(this.form, this.product)
        this.form.type = '1'

        // 处理放款时间
        const loanTimeFormObj = this.convertLoanTimeToFormData(this.form.loan_time)
        this.form = Object.assign(this.form, loanTimeFormObj)

        // // 转换城市code为城市名  测试用
        // this.product.cityNames = this.convertCityOrProvinceCodeToName(['130100', '130200'])
        // console.log('cityNames = ', this.product.cityNames)

        // 初始化formRules
        this.loanTimeTypeChangeHandler(this.form.loan_time)
        this.combinationRateTypeChangeHandler(this.form.combination_rate_type)
        this.disposableCostTypeChangeHandler(this.form.disposable_cost_type)
      } else {
        this.$notify({
          title: this.$t('operationFailed'),
          message: data['msg'],
          type: 'warning'
        })
      }
    },
    /**跳转到编辑结果组件 */
    goToEditProductResult(code) {
      this.$router.push({path:'/production/editProductResult', query:{code}})
    },
    // 检查当前表单项是否需要显示 
    isDisplay(fieldName) {
      if (fieldName) {
        // 字段在form中则显示
        return _.has(this.form, fieldName)
      }
      return false
    },
    uploadLogo(data) {
      console.log('上传logo， file= ', data)
      let param = new FormData(); //创建form对象
      param.append('img_file', data.file)
      this.$store.dispatch('uploadImg', param).then(res => {
        console.log('上传logo结果：', res)
        const { code, data } = res
        if (code === 0) {
          this.form.logo = data.img_url

          this.$notify({
            title: this.$t('operationSuccess'),
            message: this.$t('fileUploadSuccess'),
            type: 'success'
          })
        }
      }).catch(error => {
        console.error('上传logo失败：', error)
        this.$notify({
          title: this.$t('operationFailed'),
          message: this.$t('fileUploadFailed'),
          type: 'warning'
        })
      })
    },
    handleLogoSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.logo = URL.createObjectURL(file.raw);
      console.log('upload res = ', res)
      console.log('upload file = ', file)
    },
    beforeLogoUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG) {
        this.$message.error("上传的logo图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传的logo图片大小不能超过 5MB!");
      }
      return (isJPG || isPNG) && isLt5M;
    },
    // 提交或更新快速贷产品
    addOrUpdataFastProduct(fastProduct) {
      this.submitLoading = true
      let promise
      
      if (this.fastProductId) {
        promise = this.$store
          .dispatch('updateOneFastProduct', fastProduct)
      } else {
        promise = this.$store.dispatch('addOneFastProduct', fastProduct)
      }
      
      if (promise) {
        promise.then(data => {
          this.submitLoading = false;
          
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          // this.goToUserManagement()
        }).catch((error) => {
          console.error('add or update fast product has error:', error)
          this.submitLoading = false;
          let msg = this.$t('errorTips')
          if (error && error['code'] !== 0) {
            msg = error['msg']
          }
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: msg,
          })
        })
      }
    },
    // 提交或更新银行贷产品
    addOrUpdataBankProduct(bankProduct) {
      this.submitLoading = true
      let promise
      
      if (this.bankProductId) {
        promise = this.$store
          .dispatch('updateOneBankProduct', bankProduct)
      } else {
        promise = this.$store.dispatch('addOneBankProduct', bankProduct)
      }
      
      if (promise) {
        promise.then(data => {
          this.submitLoading = false
          
          if (data && data['code'] === 0) {
            this.$notify({
              title: this.$t('operationSuccess'),
              message: data['msg'],
              type: 'success'
            })
          } else {
            this.$notify({
              title: this.$t('operationFailed'),
              message: data['msg'],
              type: 'warning'
            })
          }

          // this.goToUserManagement()
        }).catch((error) => {
          console.error('add or update bank product has error:', error)
          this.submitLoading = false;
          let msg = this.$t('errorTips')
          if (error && error['code'] !== 0) {
            msg = error['msg']
          }
          this.$notify.error({
            title: this.$t('operationFailed'),
            message: msg,
          })
        })
      }
    },
    // 选中城市改变的处理方法
    cityChangeHandler(cityData) {
      console.log('city change data: ', cityData)
      if (cityData) {
        this.form.city_code = cityData.map(item => item.city_gbcode)
      } else {
        if (this.isCityMultiple) {
          this.form.city_code = []
        } else {
          this.form.city_code = ''
        }
      }
      this.$refs.form.validateField('city_code', (param) => {
        // console.log('城市校验结果：', param)
      })
    },
    // 极速贷提交处理方法
    fastProductProcess(product) {
      let submitObj = {}
      submitObj = _.pick(this.form, this.fastProductFields)

      // 处理放款时间
      const formLoanTime = this.form.loan_time
      if (formLoanTime === '1' 
        || formLoanTime === '2') {

        let loan_time = ''
        if (formLoanTime === '1') {
          // 与后台约定，使用-符号连接最大和最小放款时间，以字符串形式存储
          loan_time = `${this.form.lendingTimeFrom}-${this.form.lendingTimeTo}`
        } else if (formLoanTime === '2') {
          // 与后台约定，n天以上传字符串
          loan_time = `${this.form.lendingTimeMin}天以上`
        } 
        
        submitObj.loan_time = loan_time
      } else {
        submitObj.loan_time = formLoanTime
      }

      // 处理平均综合费率
      // if (this.form.combination_rate_type === 1 &&
      //   this.form.averageMonthlyFeeRateMin > 0 
      //   && this.form.averageMonthlyFeeRateMax > 0) {
      if (this.form.combination_rate_type === 1 &&
        this.form.averageMonthlyFeeRate > 0) {

        // // 与后台约定，使用-符号连接最大综合费率和最小综合费率，以字符串形式存储
        // const combination_rate = `${this.form.averageMonthlyFeeRateMin}-${this.form.averageMonthlyFeeRateMax}`
        // submitObj.combination_rate = combination_rate

        // 改为数字，目前只支持整数，放大100倍后存储
        submitObj.combination_rate = this.form.averageMonthlyFeeRate * 100

      } else {
        submitObj.combination_rate = 0
      }

      // 处理一次性费用
      // if (this.form.disposable_cost_type === 1 
      //   && this.form.oneTimeFeeRateMin > 0 
      //   && this.form.oneTimeFeeRateMax > 0) {
      if (this.form.disposable_cost_type === 1 
        && this.form.oneTimeFeeRate > 0) {
        // // 与后台约定，使用-符号连接最大费用和最小费用，以字符串形式存储
        // const disposable_cost = `${this.form.oneTimeFeeRateMin}-${this.form.oneTimeFeeRateMax}`
        // submitObj.disposable_cost = disposable_cost

        // 为数字，目前只支持整数，放大100倍后存储
        submitObj.disposable_cost = this.form.oneTimeFeeRate * 100
      } else {
        submitObj.disposable_cost = 0
      }

      // 处理城市
      if (this.form.city_code) {
        const cityCodes = this.form.city_code.toString()
        submitObj.city_code = cityCodes
      }

      return submitObj
    },
    // 银行贷提交处理方法
    bankProductProcess(product) {
      let submitObj = {}
      submitObj = _.pick(this.form, this.bankProductFields)

      // 处理贷款额度，银行贷的单位是万
      submitObj.min_deposit = this.form.min_deposit * 10000
      submitObj.max_deposit = this.form.max_deposit * 10000

      // 处理放款时间
      const formLoanTime = this.form.loan_time
      if (formLoanTime === '1' 
        || formLoanTime === '2') {

        let loan_time = ''
        if (formLoanTime === '1') {
          // 与后台约定，使用-符号连接最大和最小放款时间，以字符串形式存储
          loan_time = `${this.form.lendingTimeFrom}-${this.form.lendingTimeTo}`
        } else if (formLoanTime === '2') {
          // 与后台约定，n天以上传字符串
          loan_time = `${this.form.lendingTimeMin}天以上`
        } 
        
        submitObj.loan_time = loan_time
      } else {
        submitObj.loan_time = formLoanTime
      }

      // 处理平均综合费率
      // if (this.form.combination_rate_type === 1 &&
      //   this.form.averageMonthlyFeeRateMin > 0 
      //   && this.form.averageMonthlyFeeRateMax > 0) {

        // // 与后台约定，使用-符号连接最大综合费率和最小综合费率，以字符串形式存储
        // const combination_rate = `${this.form.averageMonthlyFeeRateMin}-${this.form.averageMonthlyFeeRateMax}`
        // submitObj.combination_rate = combination_rate
      if (this.form.combination_rate_type === 1 &&
        this.form.averageMonthlyFeeRate > 0) {

        // 改为数字，只能提交数字
        submitObj.combination_rate = this.form.averageMonthlyFeeRateMax
      } else {
        submitObj.combination_rate = 0
      }

      // 处理一次性费用
      if (this.form.disposable_cost_type === 1 
        && this.form.oneTimeFeeRate > 0) {
      // if (this.form.disposable_cost_type === 1 
      //   && this.form.oneTimeFeeRateMin > 0 
      //   && this.form.oneTimeFeeRateMax > 0) {
        // // 与后台约定，使用-符号连接最大费用和最小费用，以字符串形式存储
        // const disposable_cost = `${this.form.oneTimeFeeRateMin}-${this.form.oneTimeFeeRateMax}`
        // submitObj.disposable_cost = disposable_cost

        // 测试用，目前服务器只支持提交数字
        submitObj.disposable_cost = this.form.oneTimeFeeRateMax
      } else {
        submitObj.disposable_cost = 0
      }

      // 处理担保金比率
      if (this.form.collateralRatioType === 1 
        && this.form.collateralRatioMin > 0 
        && this.form.collateralRatioMax > 0) {
        // 与后台约定，使用-符号连接最大费用和最小费用，以字符串形式存储
        const disposable_cost = `${this.form.collateralRatioMin}-${this.form.collateralRatioMax}`
        submitObj.collateral = disposable_cost
      } else {
        submitObj.collateral = 0
      }

      // 处理城市
      if (this.form.city_code) {
        const cityCodes = this.form.city_code.toString()
        submitObj.city_code = cityCodes
      }

      return submitObj
    },
    // 校验字段方法
    validateOtherField(fieldName) {
      this.$refs.form.validateField(fieldName, (result) => {
        // console.log(`校验field(${fieldName})的结果：${result}`)
      })
    },
    // 放款时间改变处理方法
    loanTimeTypeChangeHandler(value) {
      if (value === 1) {
        // 添加最大，最小放款时间校验
        this.formRules.lendingTimeFrom = this.publicFormRules.lendingTimeFrom
        this.formRules.lendingTimeTo = this.publicFormRules.lendingTimeTo
        
        this.formRules = _.omit(this.formRules, ['lendingTimeMin'])
      } else if (value === 2) {
        // 添加n天以上放款时间校验
        this.formRules.lendingTimeMin = this.publicFormRules.lendingTimeMin
        this.formRules = _.omit(this.formRules, ['lendingTimeFrom', 'lendingTimeTo'])
      } else {
        this.formRules = _.omit(this.formRules, ['lendingTimeFrom', 'lendingTimeTo', 'lendingTimeMin'])
      }

      this.$refs.form.clearValidate()
    },
    // 平均每月综合费率改变处理方法
    combinationRateTypeChangeHandler(value) {
      if (value === 1) {
        // 添加最大，最小费率校验
        this.formRules.averageMonthlyFeeRateMin = this.publicFormRules.averageMonthlyFeeRateMin
        this.formRules.averageMonthlyFeeRateMax = this.publicFormRules.averageMonthlyFeeRateMax
      } else {
        this.formRules = _.omit(this.formRules, ['averageMonthlyFeeRateMin', 'averageMonthlyFeeRateMax'])
      }

      this.$refs.form.clearValidate()
    },
    // 一次性费用改变处理方法
    disposableCostTypeChangeHandler(value) {
      if (value === 1) {
        // 添加最大，最小一次性费用校验
        this.formRules.oneTimeFeeRateMin = this.publicFormRules.oneTimeFeeRateMin
        this.formRules.oneTimeFeeRateMax = this.publicFormRules.oneTimeFeeRateMax
      } else {
        this.formRules = _.omit(this.formRules, ['oneTimeFeeRateMin', 'oneTimeFeeRateMax'])
      }

      this.$refs.form.clearValidate()
    },
    // 担保金比率改变处理方法
    collateralRatioTypeChangeHandler(value) {
      if (value === 1) {
        // 添加最大，最小一次性费用校验
        this.formRules.collateralRatioMin = this.bankFormRules.collateralRatioMin
        this.formRules.collateralRatioMax = this.bankFormRules.collateralRatioMax
      } else {
        this.formRules = _.omit(this.formRules, ['collateralRatioMin', 'collateralRatioMax'])
      }

      this.$refs.form.clearValidate()
    },
    /**
     * 当前是否更新产品操作
     * 是则返回true
     */
    isUpdateProduct() {
      let result = false
      const routerPath = this.$route.path
      if ( routerPath.includes('editProduct') && (this.bankProductId || this.fastProductId) ) {
        result = true
      }
      return result
    },
    /**
     * 显示loading遮罩层
     */
    openFullScreenLoading() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t('loading') + '...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /**
     * 关闭loading遮罩层
     */
    closeFullScreenLoading() {
      if (this.loading) {
        this.loading.close()
      }
    },
    /**
     * 转换服务器存储的放款时间字符串为form的字段
     */
    convertLoanTimeToFormData(loanTimeStr) {
      const result = {}
      const loanTimeStrArr = loanTimeStr.split('-')
      if (loanTimeStrArr.length === 2) {
        result.loan_time = '1'
        result.lendingTimeFrom = loanTimeStrArr[0]
        result.lendingTimeTo = loanTimeStrArr[1]
      } else if (loanTimeStr.endsWith('天以上')) {
        result.loan_time = '2'
        result.lendingTimeMin = loanTimeStr.replace('天以上', '')
      } else {
        result.loan_time = '3'
      }
      return result
    },
    /**
     * 转换城市或省编码为名称
     */
    convertCityOrProvinceCodeToName(codes) {
      let result = []
      if (Array.isArray(codes) && codes.length > 0) {
        codes.forEach(item => {
          const name = getCityNameByCode(item)
          result.push(name)
        })
      } else if (_.isString(codes)) {
        result = getCityNameByCode(codes)
      }
      return result
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "@/styles/variables.scss";
@import "../../../icons/iconfont/iconfont.css";
.form-container {
  max-width: 1000px;
  margin: 20px auto;
  .suffix-icon {
    font-size: 30px;
    line-height: 55px;
  }
  .suffix-icon-month {
    display: inline-block;
    font-size: 18px;
    line-height: 36px;
    vertical-align: middle;
  }
  .suffix-icon-day {
    display: inline-block;
    width: 16px;
    font-size: 16px;
    line-height: 32 px;
    vertical-align: middle;
  }
  .suffix-icon-day-min {
    display: inline-block;
    width: 48px;
    font-size: 16px;
    line-height: 32 px;
    vertical-align: middle;
  }
  .lending-time-selection-box {
    margin-left: 5px;
  }
  .divider {
    height: 62px;
  }
  .rate-input {
    width: 80px;
  }
}
@media screen and (max-width: $sm){
  .form-container {
    margin: 20px;
  }
}
</style>
<style rel="stylesheet/scss" lang="scss">
.logo-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.logo-uploader {
  .el-upload:hover {
    border-color: #409eff;
  }
}
.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 158px;
  line-height: 158px;
  text-align: center;
}
.logo {
  width: 158px;
  height: 158px;
  display: block;
}
.application-input {
  margin-bottom: 10px;
  .el-input__inner {
    padding-left: 80px;
  }
}
.inner-form-item {
  margin-left: -135px;
}
.check-box-form-item {
  display: inline-block;
}
</style>


